# 用户管理 RESTful API 控制器
from flask import request, current_app
from flask_restx import Resource, abort
from flask_jwt_extended import jwt_required, get_jwt_identity, create_access_token, create_refresh_token

from app.extensions import db
from app.models.user import User
from app.utils.response import success_response, error_response
from .. import user_ns
from ..dto.user_dto import (
    user_model, user_create_model, user_update_model, 
    paginated_users_model, success_response_model, error_response_model
)

@user_ns.route('/')
class UserListResource(Resource):
    @user_ns.doc('list_users')
    @user_ns.marshal_with(paginated_users_model)
    @user_ns.param('page', '页码', type=int, default=1)
    @user_ns.param('per_page', '每页数量', type=int, default=10)
    @user_ns.param('search', '搜索关键词')
    @user_ns.param('is_active', '是否激活', type=bool)
    def get(self):
        """获取用户列表（分页）"""
        page = request.args.get('page', 1, type=int)
        per_page = min(request.args.get('per_page', 10, type=int), 100)  # 限制每页最大数量
        search = request.args.get('search', '')
        is_active = request.args.get('is_active', type=bool)
        
        # 构建查询
        query = User.query
        
        # 搜索过滤
        if search:
            query = query.filter(
                db.or_(
                    User.username.contains(search),
                    User.email.contains(search),
                    User.nickname.contains(search)
                )
            )
        
        # 状态过滤
        if is_active is not None:
            query = query.filter(User.is_active == is_active)
        
        # 分页查询
        pagination = query.paginate(
            page=page, 
            per_page=per_page, 
            error_out=False
        )
        
        users = pagination.items
        
        return {
            'users': [user.to_dict() for user in users],
            'pagination': {
                'page': pagination.page,
                'per_page': pagination.per_page,
                'total': pagination.total,
                'pages': pagination.pages,
                'has_prev': pagination.has_prev,
                'has_next': pagination.has_next,
                'prev_num': pagination.prev_num,
                'next_num': pagination.next_num
            }
        }
    
    @user_ns.doc('create_user')
    @user_ns.expect(user_create_model, validate=True)
    @user_ns.marshal_with(user_model)
    @user_ns.response(201, '用户创建成功')
    @user_ns.response(400, '无效请求', error_response_model)
    def post(self):
        """创建新用户"""
        data = request.get_json()
        
        # 检查用户名是否已存在
        if User.query.filter_by(username=data['username']).first():
            abort(400, message='用户名已存在')
        
        # 检查邮箱是否已存在
        if User.query.filter_by(email=data['email']).first():
            abort(400, message='邮箱已存在')
        
        # 创建新用户
        user = User(
            username=data['username'],
            email=data['email'],
            nickname=data.get('nickname'),
            bio=data.get('bio'),
            age=data.get('age'),
            gender=data.get('gender'),
            phone=data.get('phone'),
            birth_date=data.get('birth_date'),
            address=data.get('address'),
            avatar=data.get('avatar'),
            interests=data.get('interests'),
            website=data.get('website'),
            is_public=data.get('is_public', True)
        )
        
        # 设置密码
        user.set_password(data['password'])
        
        # 保存到数据库
        db.session.add(user)
        db.session.commit()
        
        return user.to_dict(), 201

@user_ns.route('/<int:user_id>')
@user_ns.response(404, '用户未找到', error_response_model)
class UserResource(Resource):
    @user_ns.doc('get_user')
    @user_ns.marshal_with(user_model)
    def get(self, user_id):
        """根据ID获取用户信息"""
        user = User.query.get_or_404(user_id)
        return user.to_dict()
    
    @user_ns.doc('update_user')
    @user_ns.expect(user_update_model, validate=True)
    @user_ns.marshal_with(user_model)
    @user_ns.response(403, '权限不足', error_response_model)
    @jwt_required()
    def put(self, user_id):
        """更新用户信息"""
        current_user_id = get_jwt_identity()
        current_user = User.query.get(current_user_id)
        
        # 检查权限：只有用户本人或管理员可以更新
        if current_user_id != user_id and not current_user.is_admin:
            abort(403, message='权限不足')
        
        user = User.query.get_or_404(user_id)
        data = request.get_json()
        
        # 更新用户信息
        if 'nickname' in data:
            user.nickname = data['nickname']
        if 'bio' in data:
            user.bio = data['bio']
        if 'age' in data:
            user.age = data['age']
        if 'gender' in data:
            user.gender = data['gender']
        if 'phone' in data:
            user.phone = data['phone']
        if 'birth_date' in data:
            user.birth_date = data['birth_date']
        if 'address' in data:
            user.address = data['address']
        if 'avatar' in data:
            user.avatar = data['avatar']
        if 'interests' in data:
            user.interests = data['interests']
        if 'website' in data:
            user.website = data['website']
        if 'is_public' in data:
            user.is_public = data['is_public']
        
        # 管理员可以修改系统字段
        if current_user.is_admin:
            if 'is_active' in data:
                user.is_active = data['is_active']
            if 'is_admin' in data:
                user.is_admin = data['is_admin']
        
        db.session.commit()
        return user.to_dict()
    
    @user_ns.doc('delete_user')
    @user_ns.marshal_with(success_response_model)
    @user_ns.response(403, '权限不足', error_response_model)
    @jwt_required()
    def delete(self, user_id):
        """删除用户"""
        current_user_id = get_jwt_identity()
        current_user = User.query.get(current_user_id)
        
        # 检查权限：只有用户本人或管理员可以删除
        if current_user_id != user_id and not current_user.is_admin:
            abort(403, message='权限不足')
        
        user = User.query.get_or_404(user_id)
        
        # 软删除：设置为非激活状态
        user.is_active = False
        db.session.commit()
        
        return {'success': True, 'message': '用户已删除'}

@user_ns.route('/me')
@user_ns.response(401, '未授权', error_response_model)
class CurrentUserResource(Resource):
    @user_ns.doc('get_current_user')
    @user_ns.marshal_with(user_model)
    @jwt_required()
    def get(self):
        """获取当前登录用户信息"""
        current_user_id = get_jwt_identity()
        user = User.query.get_or_404(current_user_id)
        return user.to_dict()
    
    @user_ns.doc('update_current_user')
    @user_ns.expect(user_update_model, validate=True)
    @user_ns.marshal_with(user_model)
    @jwt_required()
    def put(self):
        """更新当前登录用户信息"""
        current_user_id = get_jwt_identity()
        user = User.query.get_or_404(current_user_id)
        data = request.get_json()
        
        # 更新用户信息
        if 'nickname' in data:
            user.nickname = data['nickname']
        if 'bio' in data:
            user.bio = data['bio']
        if 'age' in data:
            user.age = data['age']
        if 'gender' in data:
            user.gender = data['gender']
        if 'phone' in data:
            user.phone = data['phone']
        if 'birth_date' in data:
            user.birth_date = data['birth_date']
        if 'address' in data:
            user.address = data['address']
        if 'avatar' in data:
            user.avatar = data['avatar']
        if 'interests' in data:
            user.interests = data['interests']
        if 'website' in data:
            user.website = data['website']
        if 'is_public' in data:
            user.is_public = data['is_public']
        
        db.session.commit()
        return user.to_dict()